package com.shitou.shitoucart.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shitou.shitoucart.config.RabbitMQConfig;
import com.shitou.shitoucart.entity.CartEntity;
import com.shitou.shitoucart.entity.MemberCartEntity;
import com.shitou.shitoucart.service.CartService;
import com.shitou.shitoucart.service.MemberCartService;
import com.shitou.shitoucommons.vo.DeleteCartVo;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.channels.Channel;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * class detail:
 *
 * @author 石头人
 */
@SuppressWarnings("all")
@Component
public class DeleteCartListener {

    @Autowired
    private MemberCartService memberCartService;
    private CartService cartService;

    /**
     * 删除购物车，可选
     * @param msg
     * @param channel
     * @param message
     */
    @RabbitListener(queues = {RabbitMQConfig.DELETE_CART})
    public void deleteCart(String msg, Channel channel, Message message){
        DeleteCartVo deleteCartVo = JSON.parseObject(msg, DeleteCartVo.class);
        long memberId = deleteCartVo.getMemberId();
        long[] spuIds = deleteCartVo.getSpuId();
        if ( spuIds.length < 0 ){
            return;
        }

        List<MemberCartEntity> memberCartEntities = memberCartService.list(new QueryWrapper<MemberCartEntity>().eq("member_id", memberId));
        List<CartEntity> list = new ArrayList<>();
        for (MemberCartEntity memberCartEntity : memberCartEntities) {
            for (long spuId : spuIds) {
                CartEntity cart = cartService.getOne(new QueryWrapper<CartEntity>().eq("id", memberCartEntity.getCartId()));
                if ( spuId == cart.getSpuId() ) {
                    cart.setStatus(0);
                    list.add(cart);
                    continue;
                }
            }
        }
        cartService.updateBatchById(list);
    }
}
